package setting

import (
	"log"
	"time"

	"github.com/go-ini/ini"
)

var (
	//Cfg ini file obj
	Cfg *ini.File
	//RunMode release or debug
	RunMode string
	//HTTPPort port to listen
	HTTPPort int
	//ReadTimeout global readtimeout
	ReadTimeout time.Duration
	//WriteTimeout global writetimeout
	WriteTimeout time.Duration
	//JwtSecret jwt sec's token string
	JwtSecret string
	//PageSize list页面的单页数量
	PageSize int
)

func init() {
	var err error
	Cfg, err = ini.Load("conf/app.ini")
	if err != nil {
		log.Fatalf("Fail to parse 'conf/app.ini':%v", err)
	}

	loadBase()
	loadServer()
	loadApp()
	loadPage()
}

func loadBase() {
	RunMode = Cfg.Section("").Key("RUN_MODE").MustString("debug")
}

func loadApp() {
	sec, err := Cfg.GetSection("server")
	if err != nil {
		log.Fatalf("Fail to get section 'server':%v", err)
	}

	JwtSecret = sec.Key("JWT_SECRET").MustString("notfindjwtsecret_ddd")
}

func loadServer() {
	sec, err := Cfg.GetSection("server")
	if err != nil {
		log.Fatalf("Fail to get section 'server': %v", err)
	}

	HTTPPort = sec.Key("HTTP_PORT").MustInt(8000)
	ReadTimeout = time.Duration(sec.Key("READ_TIMEOUT").MustInt(60)) * time.Second
	WriteTimeout = time.Duration(sec.Key("WRITE_TIMEOUT").MustInt(60)) * time.Second
}

func loadPage(){
	sec, err := Cfg.GetSection("page")
	if err != nil {
		log.Fatalf("Fail to get section 'page':#{err}")
	}
	PageSize = sec.Key("PAGE_SIZE").MustInt(20)
}
